import React, {useState, useEffect} from 'react'
import {MainBar} from "@/components/bar/bar";
import Area from "@/components/area/area";
import config from '@/config/config'
import {Select} from "antd";
import Radio from "@/pages/post/Radio";
import Vditor from 'vditor'
import './index.scss'
import 'vditor/src/assets/scss/index.scss'
import '../../iconfont.css'
import {apiPostBlog, IPostBlogData} from "@/common/apis/post";

const Post: React.FC<any> = (props) => {

  const [param, setParam] = useState({})

  const selectTags = (val: string[]) => {
    if (val && val.length > 0) {
      setParam({...param, tags: val.join("|")})
    }
  }

  const changeTitle = (title: string) => {
    setParam({...param, title})
  }

  const changeContent = (content: string) => {
    setParam({...param, content})
  }

  const selectCategory = (category_id: any) => {
    setParam({...param, category_id})
  }

  const setPublish = (publish: number) => {
    setParam({...param, publish})
  }

  const backToHome = () => {
    props.history.push('/home')
  }

  const handleSubmit = () => {
    apiPostBlog(param).then(res => {
      console.log(res)
    }).catch(err => {
      console.log(err)
    })

    // apiPostBlog
    /* cyPost('发布帖子', cyUrl([baseURL, post.base, post.createPost]),
       {token: wls.XB_token},
       qs.stringify({
         title: title,
         content: content,
         categoryId: categroy,
         tag: taglist.join(','),
         status: postAuth
       })
     ).then(() => {
       message.success({
         content: '发布成功！',
         style: {marginTop: '20vh'},
         duration: 1,
         onClose: () => {
           wls.setItem('vditorpost-content', '')
           backToHome()
         }
       })
     }).catch(err => {
       message.error({
         content: err,
         style: {marginTop: '20vh'},
         duration: 2
       })
     })*/
  }

  useEffect(() => {
    const vditor = new Vditor('post-content', {
      width: '100%',
      height: 300,
      mode: 'ir',
      placeholder: '内容（必填）\n请尽情发挥吧...\n小提示：可在 Word/Typora 等编辑器中编辑、排版后将文章内容粘贴到此处\n支持 Markdown 语法',
      blur() {
        changeContent(vditor.getValue())
      },
    })
  }, [])

  return (
    <MainBar className='page-post'>
      <Area
        title='发布帖子'
        className='page-post_post-oper-container'
        // more={{text: '草稿箱', path: '/post/draftBox'}}
      >
        <div className='post-oper-box'>
          {/* 帖子标题 */}
          <div className='post-oper-unit title-box'>
            <label className='label' htmlFor='post-title'>标题</label>
            <input
              type='text'
              className='input right'
              placeholder='标题（必填）'
              id='post-title'
              onChange={(e) => {
                changeTitle(e.target.value)
              }}
            />
          </div>

          {/* 帖子内容 */}
          <div className='post-oper-unit content-box'>
            <label className='label' htmlFor="post-content">内容</label>
            <div className={'vditor right'} id='post-content'/>
          </div>

          {/* 所在专栏 */}
          <div className='post-oper-unit category-box'>
            <label className='label' htmlFor="post-category">所在专栏</label>
            <select
              className='select right'
              id='post-category'
              onChange={(e) => {
                selectCategory(e.target.value)
              }}
            >
              {config.head.navi.map((item) => {
                return (
                  <option value={item.categoryId} key={item.categoryId}>
                    {item.page}
                  </option>
                )
              })}
            </select>
          </div>

          {/* 帖子标签 */}
          <div className='post-oper-unit tag-box'>
            <label className='label' htmlFor="">帖子标签</label>
            <Select
              mode="tags"
              dropdownClassName='post-tags'
              allowClear={true}
              open={false}
              tokenSeparators={[',', '，', ' ']}
              placeholder='输入标签（选填），以逗号或空格分隔'
              onChange={selectTags}
            />
          </div>

          {/* 阅读权限 */}
          <div className='post-oper-unit auth-box'>
            <label className='label'>阅读权限</label>
            <div className='radio-box'>
              <Radio name='post-auth' value={1} label='默认，所有用户可见' default={true} checked={setPublish}/>
              <Radio name='post-auth' value={0} label='隐藏，仅个人空间中可见' checked={setPublish}/>
            </div>
          </div>

          {/* 发布按钮 */}
          <div className='post-oper-unit submit-box'>
            <button className='button' onClick={handleSubmit}>发布</button>
          </div>
        </div>
      </Area>
    </MainBar>
  )
}

export default Post

